package com.yh.blog.controller;

import com.yh.blog.config.PersonConfig;
import com.yh.blog.domain.Comments;
import com.yh.blog.domain.Users;
import com.yh.blog.service.BlogService;
import com.yh.blog.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * 评论前台展示控制层
 */
@Controller
public class CommentsController {

    @Autowired
    private CommentsService commentsService;
    @Autowired
    private BlogService blogService;

//    从配置中拿到评论头像
    @Value("${comments.img}")
    private String commentImg;

//    跳转到博客详情页面中th:fragment=commentList的标签
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId") Integer blogId, Model model){
        model.addAttribute("comments",this.commentsService.listCommentsByBlogId(blogId));
        return "blog_detail :: commentList";
    }

//    新增博客
    @PostMapping("/comments")
    public String post(Comments comments, HttpSession session){
//        这里是判断 当前博客中评论的人是否是站长，是|不是 进行不同的处理
        int blogId=comments.getBlogId();
        comments.setBlog(this.blogService.detail(blogId));
        Users user=(Users) session.getAttribute("user");
        if(user!=null){
            comments.setImg(user.getImg());
            comments.setAdmin_comment(true);
        }else {
            comments.setImg(commentImg);
        }
        this.commentsService.append(comments);
        return "redirect:/comments/"+blogId;
    }
}
